import cv2
import numpy as np


def binarize(p: np.ndarray, limit):
    row = p.shape[0]
    col = p.shape[1]
    for i in range(row):
        for j in range(col):
            if p[i][j] > limit:
                p[i][j] = 255
            else:
                p[i][j] = 0
    return p


def erode(img: np.ndarray, kernel: np.ndarray):
    padding = int(kernel.shape[0] / 2)
    length = int(kernel.shape[0])
    for i in range(padding,length-padding):
        for j in range(padding,length-padding):
            if fit(i,j,img,kernel):
                img[i][j]=0
            else:
                img[i][j]=255
    img[0:padding - 1][:] = 0
    img[length - padding:length][:] = 0
    img[:][0:padding - 1] = 0
    img[:][length - padding:length] = 0
    return img

def fit(i,j,img:np.ndarray,kernel:np.ndarray):
    for x in range((i-kernel.shape[0]//2),i+kernel.shape[0]//2):
        for y in range(j-kernel.shape[1]//2,j+kernel.shape[1]//2):
            if img[x][y] == 255 and kernel[x][y]==1:
                continue
            else:
                return False
    return True


if __name__ == '__main__':
    I = cv2.imread('/Users/guasen/PycharmProjects/PhotoProcess/resource/test.png', 0)
    img = binarize(I, 200)
    ret, img = cv2.threshold(I, 127, 255, cv2.THRESH_BINARY_INV)
    m,n =img.shape

    kernel = np.ones((3, 3), np.uint8)
    r = cv2.erode(img, kernel, iterations=1)
    # r = erode(img,kernel)
    # 边缘提取
    e = img - r

    cv2.imshow('img', img)
    cv2.imshow('erode', r)
    cv2.imshow('edge', e)
    cv2.imwrite('edge.png', e)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
